const app = getApp();
let api = require('../../../utils/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    invoicelist: [],
    titleTop: '', //区域离顶部的高度
    scrollTop: 0, //滑动条离顶部的距离
    Idlist: [],
    totalPrice: 0,
    totalNum: 0,
    ids: [], // id
    disable: true
  },
  onShow: function () {
    this.getinvoiveList(this.data.currentIndex);
  },
  // 发票管理
  getinvoiveList: function (type) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    let parm = {
      state: type
    }
    api._get('/omc/invoice/list', parm, token).then(res => {
      if (res.code == 200) {
        res.result.checked = false;
        // 创建临时商品合集列表
        let invoiveList = res.result;
        // 循环加入checked属性
        invoiveList.forEach(ele => {
          ele.checked = false

        });
        // 更改字段
        invoiveList.forEach(item => {
          item.orderId = item.id,
            item.invoicePrice = item.amount
        })
        // 临时商品列表赋值给全局商品列表
        that.setData({
          invoicelist: invoiveList
        });

      }
    })
  },
  titleClick: function (e) {
    let that = this;
    if (e.currentTarget.dataset.idx == 0) {
      that.getinvoiveList(0);
    } else if (e.currentTarget.dataset.idx == 1) {
      that.getinvoiveList(1);
    }
    this.setData({
      // 拿到当前索引并动态改变
      currentIndex: e.currentTarget.dataset.idx,
    })
  },
  /**
   * @param {*} 
   * 商品选中做什么?
   * 1.计算价格 统计数量?
   * 2.改变选中框状态
   * 3.把选中数据存储到本地
   */
  checkboxChange: function (e) {
    const id = e.currentTarget.dataset.id;
    let {
      invoicelist
    } = this.data;
    // 找到对应的商品
    let index = invoicelist.findIndex(ele => ele.id === id);
    // 反选状态
    invoicelist[index].checked = !invoicelist[index].checked;
    console.log(invoicelist[index].checked);
    if (invoicelist[index].checked == true) {
      this.setData({
        disable: false
      })
      // 计算总价
      let totalPrice = 0,
        totalNum = 0;
      // 把选中数据存储到本地
      invoicelist.forEach(ele => {
        // console.log(ele.checked);
        if (ele.checked) {
          totalPrice += ele.amount;
          totalNum = invoicelist.filter(ele => ele.checked).length;
          let localInvoiceList = invoicelist.filter(ele => ele.checked);
          let PriceAndNum = [{
            totalPrice,
            totalNum
          }];
          // 存到本地缓存中
          wx.setStorageSync("InvoiceList", localInvoiceList);
          wx.setStorageSync("PricendNum", PriceAndNum);
        } else {

        }
        // 把信息赋值到全局
        this.setData({
          invoicelist,
          totalPrice,
          totalNum
        })
      })
    } else {

    }

  },
  // 提交
  nextstep(e) {
    wx.navigateTo({
      url: '../billing/billing'
    })
  }
})